// middlewares/authorizeRequest.middleware.js
import { StatusCodes } from "http-status-codes";
import ApplicationError from "../libs/errors/application.error.js";

export default (allowedRoles, condition) => {
  return async (req, res, next) => {
    const user = req.user;
    
    console.log("=============================================");
    console.log("Debug authorizeRequest middleware");
    console.log("User:", user ? {
      id: user._id,
      email: user.email,
      role: user.role,
    } : null);
    console.log("Allowed roles:", allowedRoles);
    console.log("User has allowed role?", Array.isArray(allowedRoles) 
      ? allowedRoles.includes(user?.role) 
      : user?.role === allowedRoles);
    console.log("URL:", req.originalUrl);
    console.log("Method:", req.method);
    console.log("=============================================");

    if (!user) {
      throw new ApplicationError(
        StatusCodes.UNAUTHORIZED, // Just use the number directly
        "Not authorized",
        StatusCodes.UNAUTHORIZED
      );
    }

    let isAllowed = Array.isArray(allowedRoles)
      ? allowedRoles.includes(user.role)
      : user.role === allowedRoles;
      
    console.log("Initial isAllowed:", isAllowed);
    
    if (condition && typeof condition === "function") {
      const conditionResult = await condition(user, req);
      console.log("Condition function result:", conditionResult);
      isAllowed = conditionResult;
    }
    
    console.log("Final isAllowed:", isAllowed);

    if (isAllowed) {
      console.log("Access allowed, proceeding to next middleware");
      next();
    } else {
      console.log("Access denied, throwing 403 error");
      throw new ApplicationError(
        StatusCodes.FORBIDDEN, // Just use the number directly 
        "Access is forbidden",
        StatusCodes.FORBIDDEN
      );
    }
  };
};